import React, { Component } from 'react'
import { Spin } from 'antd'
import './index.css'
import ImageWidget from '../ImageWidget'

/**
 * @author liu_jshan
 * @version 1.0
 * @prop {
 *  src: img标签的src string
 *  alt: img标签的alt string
 *  isCircle: 是不是圆形头像 boolean 
 *  onClick: 点击事件
 *  style: 样式,
 *  rotating: 鼠标移入时头像旋转，圆形头像才能使用 boolean
 * }
 */
class Avatar extends Component {

    constructor(props) {
        super(props)
        this.state = {
            src: null,
            imgClassName: 'avatar-img',
            loading: true,
            imgStyle: {}
        }
    }

    async componentDidMount() {
        let src = this.props.src ? this.props.src : null
        let alt = this.props.alt ? this.props.alt : null
        let imgClassName = this.props.isCircle === true ? 'avatar-img circle-img' : 'avatar-img'

        await new Promise((resolve) => {
            this.setState({
                src,
                alt,
                imgClassName
            }, resolve)
        })

        await new Promise((resolve) => {
            this.setState({ loading: false }, resolve)
        })
    }

    //鼠标移入事件
    onMouseEnter = async () => {
        let imgStyle = this.state.imgStyle
        await new Promise((resolve) => {
            this.setState({
                imgStyle: {
                    ...imgStyle,
                    animation: 'rotate 30s ease infinite'
                }
            }, resolve)
        })
    }

    //鼠标移出事件
    onMouseLeave = async () => {
        let imgStyle = this.state.imgStyle
        await new Promise(resolve => {
            this.setState({
                imgStyle: {
                    ...imgStyle,
                    animation: null
                }
            }, resolve)
        })
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <div className='avatar-main'
                style={this.props.style}
            >
                <ImageWidget
                    className={this.state.imgClassName}
                    src={this.state.src}
                    alt={this.state.alt}
                    style={this.state.imgStyle}
                    onMouseEnter={this.props.isCircle === true && this.props.rotating === true ? this.onMouseEnter : null}
                    onMouseLeave={this.props.isCircle === true && this.props.rotating === true ? this.onMouseLeave : null}
                    onClick={this.props.onClick}
                ></ImageWidget>
            </div>
        )
    }
}

export default Avatar
